#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <memory>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->initConnect();
}



MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initConnect()
{
    connect(ui->cltrbarwidget,&ctrlbar::signalPlyaOrPause,this,&MainWindow::onPlayOrPause);

}

int MainWindow::message_loop(void* arg)
{
    ijkmp *mp = (ijkmp*) arg;
    while(1){
        AVMessage msg;
        int ret=0;
        ret = mp->ijkmp_get_msg(&msg,1);
        if(ret<0){
            std::cout<<"ret = "<<ret<<std::endl;
            break;
        }
        switch (msg.what) {
        case FFP_MSG_PREPARED:
            mp->ijkmp_start();
            break;
        case MSG_FULSH:
            std::cout<<__FUNCTION__<< "msg_flush:" << msg.what <<std::endl;
            break;
        default:
            std::cout<<__FUNCTION__<< "default:" << msg.what <<std::endl;
            break;
        }
       // qDebug("gogogogo");
        //break;
        std::cout<<__FUNCTION__<<" is running"<<std::endl;
    }
//    qDebug("ober");
    return 0;
}

int MainWindow::Outputvideo(const Frame *frame)
{
    return ui->showwidget->Draw(frame);
}



void MainWindow::onPlayOrPause()
{
//    printf("1");
   int ret =0 ;
   qDebug("1");
   if(!mp_){
       mp_ =  std::unique_ptr<ijkmp>(new ijkmp());
       if(!mp_){
           qDebug("ijkmp error");
           return ;
       }
       qDebug("2");
       //1
       ret= mp_->ijkmp_create(std::bind(&MainWindow::message_loop,this,std::placeholders::_1));
       if(ret<0){
           qDebug("ijkmp_create failed");
           return ;
       }
       mp_->ijk_addvideoRefleshcallback(std::bind(&MainWindow::Outputvideo,this,std::placeholders::_1));
       //2.
       qDebug("3");
       ret = mp_->ijkmp_set_data_source("text.mp4");
       if(ret<0){
           qDebug("ijkmp_set_data_source fialde");
           return;
       }
       //3
       qDebug("4");
       ui->showwidget->StartPlay();
       ret =  mp_->ijkmp_prepare_async();
       if(ret<0){
           qDebug("ijkmp_prepare fialde");
           return;
       }qDebug("5");
   }else{

   }

}

void MainWindow::onStop()
{

}

